
var http = require('koa2-request');
const fs = require('fs')
const path = require('path')
const fileName = path.resolve(__dirname,'./AccessToen.json')

const wxParams = {
    appid:'wxbeaeb1c48efb385c',
    secret:'ea0822c57f63ca7766521b23492ec77c',
    // token:'fzowk3bttij1wbdyah50rtsu50vg5itu'
}
const utlAccessToken = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxbeaeb1c48efb385c&secret=ea0822c57f63ca7766521b23492ec77c'

//更新AccessToken
const upDataAccessToken= async ()=>{
    const {body} = await http({
        methods:'GET',
        url:utlAccessToken,
        data:wxParams
    })
    let AccessToken = JSON.parse(body).access_token
    if(AccessToken){
        //写入文件，并且记录服务器时间
        fs.writeFileSync(fileName,JSON.stringify({access_token:AccessToken,creare_time:new Date()}))
    }else{
        //重新获取
        await upDataAccessToken()
    }
}

//读取AccessToken
const getAccessToken = async ()=>{
    try {
        const read = fs.readFileSync(fileName,'utf-8')
        const readObj = JSON.parse(read)
        const createTime = new Date(readObj.creare_time).getTime()
        const nowTime = new Date().getTime()
        if((nowTime - createTime) / 1000 >= 7200){ //当前时间减去创建时间除以1000大于7200 说明已经过期
            await upDataAccessToken()//过期则重新获取
            await getAccessToken()
        }
        return readObj.access_token//返回accesstoken值
        
    } catch (error) {
        //重新获取
        await upDataAccessToken()
        await getAccessToken()
    }
}

//定时执行获取
setInterval(async()=>{
    await upDataAccessToken
    await getAccessToken()
},(7200-300)*1000)

module.exports=getAccessToken